
from meta_service.ucentre import AnyLancer
from meta_service.ucentre import GLOABL_DB
from meta_service.ucentre import REVIEWTYPEID

from meta_service.utils import format_title,download_pdf
from copy import copy,deepcopy


class Review:

    def __init__(self,review_key_value:dict):
        self.review_key_value_dict = review_key_value
    
    def HasKey(self,key):
        return key in self.review_key_value_dict
    
    def GetKey(self,key):
        if key in self.review_key_value_dict:
            return self.review_key_value_dict[key]
        return None
    
    def __get_leading_numbers(self,line:str):
        num = None
        try:
            line = line.strip()
            numbers = ""
            NUMBERS = [ str(i) for i in range(0,10) ]
            for ch in line:
                if ch in NUMBERS:
                    numbers += ch
                else:
                    break
            num = int(numbers)
        except Exception as e:
            print(f"error when get leading number in {line}")
            num = None
        return num
    
    def TryGetRatingScore(self,key="rating"):
        if key not in self.review_key_value_dict:
            return None
        value = str(self.review_key_value_dict[key])
        score = self.__get_leading_numbers(value)
        return score



class OVire(AnyLancer):

    def __init__(self, entry_id: str = None) -> None:
        super().__init__(entry_id)

    def __reset(self):
        self.title = ""
        self.page_url = ""
        self.site_url = ""
        self.authors = []
        self.summary = ""
        # private attr
        self.views:list[Review] = []
        self.keywords:list[str] = []
    
    def from_json(self,data:dict):
        """
        从dict中构造对象
        """
        if "title" not in data:
            print(f"no title in data, error: {data}")
            return None
        self.title = str(data.get("title")).replace("\n","").replace("\t","")
        self.site_url = data.get("url",None)
        self.page_url = data.get("pdf",None)
        author = data.get("author",[])
        if isinstance(author,str):
            self.authors = [author]
        elif isinstance(author,list):
            self.authors = author
        else:
            self.authors = [str(author)]
        self.summary = data.get("abstract",None)
        self.keywords = data.get("keywords",[])
        views = data.get("views",[])
        if isinstance(views,list):
            for item in views:
                if isinstance(item,dict):
                    self.views.append(Review(deepcopy(item)))
        return self

    def get_keywords(self):
        return self.keywords
    
    def get_views_count(self):
        return len(self.views)
    
    def get_views(self):
        return self.views
    

